package com.bmps.springcloud.insuredmicroservice.service.webservice;


import com.bmps.springcloud.insuredmicroservice.webservice.CallService;
import com.bmps.springcloud.insuredmicroservice.webservice.CallServiceFactory;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.net.URL;

/**
 * @Author :  zlc
 * @date : 2019/8/14 17:19
 **/
@Service
public class WebServiceImpl implements WebService {

    private static final Logger log = LoggerFactory.getLogger(WebServiceImpl.class);

    @Value("${webservice.url}")
    @NotNull
    private String url;
    @NotNull
    @Value("${webservice.connection-timeout}")
    private Long connectionTimeout;
    @NotNull
    @Value("${webservice.receive-timeout}")
    private Long receiveTimeout;

    @Override
    public String callService (String request, String serviceName, String symbol) {
        String callResult = "";
        Client proxy = null;
        //调用webservice接口地址
        try {
            CallServiceFactory factory = new CallServiceFactory(new URL(url));
            CallService callService = factory.getCallServicePort();
            // 连接参数设定
            proxy = ClientProxy.getClient(callService);
            HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
            HTTPClientPolicy policy = new HTTPClientPolicy();
            // 连接超时时间
            policy.setConnectionTimeout(connectionTimeout);
            // 请求超时时间,设置太短会出现核心还没返回就请求异常
            policy.setReceiveTimeout(receiveTimeout);
            conduit.setClient(policy);
            callResult = callService.invoke(serviceName, symbol, "Password", request, null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求报文" + request + " 调用核心webservice异常" + e.getMessage());
        } finally {
            if (proxy != null) {
                try {
                    proxy.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                proxy.destroy();
            }
        }
        return callResult;
    }
}
